package cn.mall.server.controller;


import cn.mall.common.constant.MemberResponseVo;
import cn.mall.common.utils.R;
import cn.mall.common.vo.MemberEntity;
import cn.mall.server.VO.UserLoginVo;
import cn.mall.server.openfeign.MemberFeignController;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

import static cn.mall.common.constant.CartConstant.USER_PREFIX;


@RestController
public class LoginController {
    @Autowired
     private RedisTemplate redisTemplate;
    @Autowired
    private MemberFeignController memberFeignController;
    @PostMapping("auth/login")
    public R Login(@RequestBody UserLoginVo loginVo, HttpServletResponse response){
        System.out.println("loginVo = " + loginVo);
        R r = memberFeignController.login(loginVo);
        System.out.println("r.getCode() = " + r.getCode());
        if (!r.getCode().equals(15003)) {
            Map<String, MemberResponseVo> memberVO = (Map<String, MemberResponseVo>) r.get("data");
            Cookie cookie = new Cookie("userId",String.valueOf(memberVO.get("id")));
            cookie.setMaxAge(60*60*60 * 60);// 设置为30mi
            cookie.setPath("/");
            cookie.setHttpOnly(true);
            response.addCookie(cookie);
            redisTemplate.setHashKeySerializer(new StringRedisSerializer());
            redisTemplate.setHashValueSerializer(new StringRedisSerializer());

            BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(USER_PREFIX + JSON.toJSONString(memberVO.get("id")));
            hashOps.put("userData", JSON.toJSONString(memberVO));
            /* redisTemplate.opsForHash().put(JSON.toJSONString(USER_PREFIX),JSON.toJSONString(memberVO.get("id")),JSON.toJSONString(memberVO));*/
            System.out.println("================"+USER_PREFIX + JSON.toJSONString(memberVO.get("id")));

        }

        System.out.println("r = " + r);
        return r;
    }


}
